<template>
<div class="upload">
  <!-- Mock 开关提示 -->
  <div style="margin-bottom: 15px; padding: 10px; background-color: #f0f9ff; border-left: 4px solid #1890ff; border-radius: 4px;">
    <p style="margin: 0; color: #666; font-size: 14px; line-height: 1.5;">
      <strong>💡 提示：</strong>将 Mock 数据关闭即可正常使用图片上传和邮箱发送功能。<br>
      <strong>⚠️ 注意：</strong>Mock 开启后首页的图表数据将消失（此数据为模拟数据，未写入真实接口）
    </p>
  </div>
  
  <!-- Mock 开关 -->
  <div class="mock-switch" style="margin-bottom: 20px;">
    <span style="margin-right: 10px;">Mock 数据:</span>
    <el-switch 
      v-model="mockEnabled" 
      class="ml-2" 
      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" 
      @change="toggleMock"
    />
    <span style="margin-left: 10px; color: #666;">
      {{ mockEnabled ? '已开启' : '已关闭' }}
    </span>
  </div>
  
  <el-upload
    class="avatar-uploader"
    action="http://127.0.0.1:8000/api/upload_picture/"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :on-error="handleError"
    :before-upload="beforeAvatarUpload"
    name="file"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</div>
      <el-divider />
<p>下列的邮箱发送功能真实可用，但是需要在django项目中配置邮箱发送功能</p>
<div class="send_mail">
  <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" @submit.prevent>
    <el-form-item label="邮件主题" prop="subject">
      <el-input
        v-model="emailForm.subject"
        placeholder="请输入邮件主题"
        clearable />
    </el-form-item>
    
    <el-form-item label="消息内容" prop="message">
      <el-input
        v-model="emailForm.message"
        type="textarea"
        :rows="4"
        placeholder="请输入邮件内容"
        clearable />
    </el-form-item>
    
    <el-form-item label="收件人列表" prop="recipients">
      <el-input
        v-model="emailForm.recipients"
        type="textarea"
        :rows="3"
        placeholder="请输入收件人邮箱，多个邮箱用逗号分隔"
        clearable />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSendEmail">发送邮件</el-button>
      <el-button @click="resetEmailForm">重置</el-button>
    </el-form-item>
  </el-form>
</div>      
</template>

<script lang="ts" setup>
import { sendEmailAPI } from "@/api/test";
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, FormRules } from 'element-plus'

const imageUrl = ref('')
const mockEnabled = ref(import.meta.env.VITE_USE_MOCK === 'true')  // Mock 开关状态，默认开启

// 邮件表单数据
const emailForm = ref({
  subject: '',
  message: '',
  recipients: ''
})

// 邮件表单验证规则
const emailRules = {
  subject: [
    { required: true, message: '请输入邮件主题', trigger: 'blur' },
    { min: 3, max: 100, message: '主题长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  message: [
    { required: true, message: '请输入邮件内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '内容长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  recipients: [
    { required: true, message: '请输入收件人邮箱', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback(new Error('请输入收件人邮箱'))
          return
        }
        // 简单的邮箱格式验证
        const emails = value.split(',').map(email => email.trim())
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        const invalidEmails = emails.filter(email => !emailRegex.test(email))
        
        if (invalidEmails.length > 0) {
          callback(new Error(`邮箱格式不正确: ${invalidEmails.join(', ')}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const emailFormRef = ref()

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // Django 返回的格式：{success: true, message: "上传成功", data: {url: "..."}}
  // console.log('后端返回数据:', response)
  // console.log('上传文件信息:', uploadFile)
  
  if (response && response.success) {
    // 使用后端返回的完整 URL - 使用正确的环境变量名
    const backendUrl = import.meta.env.VITE_BACKEND_URL || 'http://127.0.0.1:8000'
    // 确保 URL 格式正确，移除可能的末尾斜杠
    const cleanBackendUrl = backendUrl.replace(/\/$/, '')
    imageUrl.value = cleanBackendUrl + response.data.url
    // console.log('完整图片URL:', imageUrl.value)
    // console.log('后端返回的相对URL:', response.data.url)
    ElMessage.success(response.message || '上传成功！')
  } else {
    // 如果后端返回失败，使用本地预览作为备选
    // console.log('使用本地预览')
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    ElMessage.warning('后端返回异常，使用本地预览')
  }
}

const handleError: UploadProps['onError'] = (error, uploadFile) => {
  // console.error('上传错误:', error)
  ElMessage.error('上传失败，请检查网络连接')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG or PNG format!')  
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 发送邮件
const handleSendEmail = () => {
  emailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {

      console.log('邮件数据:', emailForm.value)
      
      // 处理收件人列表 - 分割并清理邮箱地址
      const recipients = emailForm.value.recipients
        .split(',')
        .map(email => email.trim())
        .filter(email => email)
      console.log('处理后的收件人列表:', recipients);
      
      const emailData = {
        subject: emailForm.value.subject,
        message: emailForm.value.message,
        recipients: recipients
      }
      
      try {
        await sendEmailAPI(emailData)
        console.log('处理后的邮件数据:', emailData)
        ElMessage.success('邮件发送成功！')
      } catch (error) {
        console.error('邮件发送失败:', error)
        ElMessage.error('邮件发送失败，请重试')
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
      return false
    }
  })
}

// 重置邮件表单
const resetEmailForm = () => {
  emailFormRef.value?.resetFields()
  emailForm.value = {
    subject: '',
    message: '',
    recipients: ''
  }
  ElMessage.info('表单已重置')
}

// Mock 开关切换函数 - 模拟开关，实际通过环境变量控制
const toggleMock = (value: boolean) => {
  // 由于 Mock.js 无法动态卸载，这里提供用户操作指引
  ElMessage.warning('Mock 状态需要通过修改环境变量控制')
  
  if (value) {
    ElMessage.info('请设置 .env.development 中 VITE_USE_MOCK=true 并重启开发服务器')
  } else {
    ElMessage.info('请设置 .env.development 中 VITE_USE_MOCK=false 并重启开发服务器')
  }
  
  // 恢复开关状态（因为实际无法改变）
  setTimeout(() => {
    mockEnabled.value = import.meta.env.VITE_USE_MOCK === 'true'
  }, 100)
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>